<?php

namespace App\Listeners;


use App\Events\Event;
use App\Events\WechatEvent;
use App\Model\Wechat\WechatConfig;
use EasyWeChat\Message\Text;
use EasyWeChat\Foundation\Application;


class WechatListener extends  Listener
{
    protected $app;
    protected $hosturl;
    protected $lesson_template;
    protected $homework_template;
    /**
     * @param WechatEvent $event
     */
    public function handle(WechatEvent $event)
    {
        $this->init();
        switch($event->action)
        {
            case Event::MESSAGE:
                $this->sendText($event); break;
            case Event::NOTICE:
                $this->sendNotice($event); break;
            case Event::TASK:
                $this->sendTask($event); break;
            default: break;
        }
    }

    /**
     * 发送文字消息
     * @param WechatEvent $event
     * @return array
     */

    protected function sendText(WechatEvent $event)
    {
        try {
            $message = $this->textMessage($event->content);
            $this->app->staff->message($message)->to($event->openid)->send();
        } catch (\Exception $e) {
            throw $e;
        }
    }

    /**
     * 初始化微信app
     *
     */
    protected function init()
    {
        $wechat = WechatConfig::find(1);
        $options = [
            'debug'  => true,
            'app_id' => $wechat->appid,
            'secret' => $wechat->secret,
            'token'  => $wechat->token,
            'aes_key' => $wechat->aes_key, // 可选
            'log' => [
                'level' => 'debug',
                'file'  => '/tmp/easywechat.log', // XXX: 绝对路径！！！！
            ],
            //...
        ];
        $this->hosturl = $wechat->url;
        $this->homework_template = $wechat->homework_template;
        $this->lesson_template = $wechat->lesson_template;
        $this->app = new Application($options);
    }

    /**
     * 构建文字消息
     * @param $data
     * @return Text
     *
     */
    protected function textMessage($data)
    {
        $text = new Text();
        $text['content'] = $data;
        return $text;
    }

    /**
     * 单发上课模板消息
     * @param Request $request
     * @return array
     */

    protected function sendNotice(WechatEvent $event)
    {
        try {
            $notice = $this->app->notice;
            $url = $this->hosturl.'/wechat/authorize/schedule';
            if($this->lesson_template){
                $templateId = $this->lesson_template;
            }else{
                $templateId = $this->getTemplate();
            }
            $userId = $event->openid;
            $data = array(
                "userName"  => $event->content->username,
                "courseName"   => $event->content->coursename,
                "date"  =>  $event->content->date,
                "remark" =>  $event->content->remark,
            );
            $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($userId)->send();
        } catch (\Exception $e) {
            throw $e;
        }
    }

    /**
     * 单发作业模板消息
     * @param Request $request
     * @return array
     */

    protected function sendTask(WechatEvent $event)
    {
        try {
            $notice = $this->app->notice;
            $url = $this->hosturl.'/wechat/authorize/homepage';
            if($this->homework_template){
                $templateId = $this->homework_template;
            }else{
                $templateId = $this->getTemplate();
            }
            $userId = $event->openid;
            $data = array(
                "first"  => $event->content->title,
                "keyword1"   => $event->content->time,
                "keyword2"  =>  $event->content->coursename,
                "keyword3" =>  $event->content->task_title,
                "keyword4" => $event->content->task_detail,
                "remark" => $event->content->remark
            );
            $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($userId)->send();
        } catch (\Exception $e) {
            throw $e;
        }
    }


    /**
     * 获取模板id
     * @param Request $request
     * @return array
     */

    protected function getTemplate()
    {
        try {
            $notice = $this->app->notice;
            $result = $notice->getPrivateTemplates();
            foreach ($result['template_list'] as $item){
                if($item['title'] == '课程开课通知'){
                    return $item['template_id'];
                }
            }
        } catch (\Exception $e) {
            throw $e;
        }
    }

}
